﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Southridge.Data 
{
    public enum PropertyType
    {
        SingleFamily = 0x1,
        MultiFamily = 0x2,
        Condominium = 0x4,
        TownHome = 0x8,
        Land = 0x10,
        Commercial = 0x20
    };

    public class Database
    {
        static string _path = "xmlfile1.xml";
        public static string Path { get; set; }

        static XDocument _document;
        private static XDocument Document
        {
            get
            {
                if (_document == null)
                {
                    _document = XDocument.Load(_path);
                }

                return _document;
            }
        }

        static List<State> _states;
        public static List<State> States
        {
            get
            {
                if (_states == null)
                {
                    var states = from s in Document.Descendants(@"State")
                                 select s;
                    List<State> statestoreturn = new List<State>();
                    foreach (XElement e in states)
                    {
                        State s = new State()
                        {
                            ID = e.Attribute("Id").Value,
                            Description = e.Attribute("Description").Value
                        };

                        var counties = from c in e.Descendants("County")
                                       select new County()
                                       {
                                           Id = c.Attribute("Id").Value,
                                           Name = c.Attribute("Name").Value,
                                           State = s.ID
                                       };

                        s.County = counties.ToList<County>();

                        foreach (County county in s.County)
                        {
                            county.Neighborhood.AddRange(Neighborhoods.Where((n) => n.CountyId == county.Id));
                        }

                        statestoreturn.Add(s);
                    }
                    _states = statestoreturn;
                } 
                return _states ;
            }

            
        }

        static List<Neighborhood> _neighborhoods; 
        public static List<Neighborhood> Neighborhoods 
        { 
            get
            { 
                if ( _neighborhoods == null ) 
                { 
                    var neighborhoods = from n in Document.Descendants("Neighborhood")
                        select new Neighborhood() { 
                            Id= ReaderHelpers.IntTryParseDefault ( n.Attribute("Id").Value, 0 ), 
                            Name = n.Attribute("Name").Value , 
                            CountyId  =  n.Attribute("CountyId").Value  ,
                            IsHighGrowth = ReaderHelpers.XAttributeBoolTryParse(n.Attribute("IsHighGrowth") ),
                            IsNearCenterCity = ReaderHelpers.XAttributeBoolTryParse(n.Attribute("IsNearCenterCity") ),
                            IsNearDining = ReaderHelpers.XAttributeBoolTryParse(n.Attribute("IsNearDining") ),
                            IsNearParks = ReaderHelpers.XAttributeBoolTryParse(n.Attribute("IsNearParks") ),
                            IsNearCommunityCenter = ReaderHelpers.XAttributeBoolTryParse(n.Attribute("IsNearCommunityCenter") ),
                            IsNearFamilyActivities = ReaderHelpers.XAttributeBoolTryParse(n.Attribute("IsNearFamilyActivities") ),
                            IsNearShopping = ReaderHelpers.XAttributeBoolTryParse(n.Attribute("IsNearShopping") ) 
                        };

                    _neighborhoods = neighborhoods.ToList<Neighborhood>(); 
                } 
                return _neighborhoods ; 
            } 
        } 


        static List<Profile> _profiles;
        public static List<Profile> Profiles
        {
            get
            {
                if (_profiles == null)
                {
                    var profiles = from s in Document.Descendants(@"Profiles")
                                   select s;
                    List<Profile> profilestoreturn = new List<Profile>();
                    foreach (XElement e in profiles.Elements())
                    {
                        Profile p = new Profile()
                        {
                            Address1 = e.Attribute("Address1").Value,
                            Address2 = e.Attribute("Address2").Value,
                            City = e.Attribute("City").Value,
                            MobilePhoneNo = e.Attribute("MobilePhoneNo").Value,
                            HomePhoneNo = e.Attribute("HomePhoneNo").Value,
                            LastName = e.Attribute("LastName").Value,
                            FirstName = e.Attribute("FirstName").Value,
                            Email = e.Attribute("Email").Value,
                            ZipCode = e.Attribute("ZipCode").Value
                        };

                        var preferences = from c in e.Elements("Preference")
                                          select new Preference()
                                          {
                                              HasView = ReaderHelpers.BoolTryParseDefault(c.Attribute("HasView").Value, false),
                                              HasWaterFront = ReaderHelpers.BoolTryParseDefault(c.Attribute("HasWaterFront").Value, false),
                                              Acreage = ReaderHelpers.DoubleTryParse(c.Attribute("Acreage").Value),
                                              MinBaths = ReaderHelpers.DoubleTryParse(c.Attribute("MinBaths").Value),
                                              MinGarage = ReaderHelpers.IntTryParseDefault(c.Attribute("MinGarage").Value, 0),
                                              MinRooms = ReaderHelpers.IntTryParseDefault(c.Attribute("MinRooms").Value, 0),
                                              PriceStart = ReaderHelpers.IntTryParseDefault(c.Attribute("PriceStart").Value, 0),
                                              PriceStop = ReaderHelpers.IntTryParseDefault(c.Attribute("PriceStop").Value, 0),
                                              SquareFootage = ReaderHelpers.DoubleTryParse(c.Attribute("SquareFootage").Value),
                                              YearBuilt = ReaderHelpers.IntTryParseDefault(c.Attribute("YearBuilt").Value, 0)

                                          };

                        p.Preference = preferences.First<Preference>();
                        profilestoreturn.Add(p);
                    }
                    _profiles = profilestoreturn; 
                } 
                return _profiles;
            }

        }

        public static List<Listing> Listings
        {
            get
            {
                try
                {
                    var listings = from s in Document.Descendants(@"Listings").Descendants()
                                   select new Listing()
                                   {
                                       MLS = s.Attribute("MLS").Value,
                                       Title = s.Attribute("Title").Value,
                                       Description = s.Attribute("Description").Value,
                                       Address1 = s.Attribute("Address1").Value,
                                       Address2 = s.Attribute("Address2").Value,
                                       BathroomCount = ReaderHelpers.DoubleTryParse(s.Attribute("BathroomCount").Value ),
                                       BedroomCount = ReaderHelpers.IntTryParseDefault(s.Attribute("BedroomCount").Value, 0),
                                       City = s.Attribute("City").Value,
                                       ZipCode = s.Attribute("ZipCode").Value,
                                       ClientRating = ReaderHelpers.IntTryParseDefault(s.Attribute("ClientRating").Value, 0),
                                       Year = ReaderHelpers.IntTryParseDefault(s.Attribute("Year").Value, 0),
                                       SquareFootage = ReaderHelpers.IntTryParseDefault(s.Attribute("SquareFootage").Value, 0),
                                       Price = ReaderHelpers.IntTryParseDefault(s.Attribute("Price").Value, 0),
                                       HasAppt = ReaderHelpers.BoolTryParseDefault(
                                                  (s.Attribute("HasAppt") != null) ?
                                                       s.Attribute("HasAppt").Value : "", false),
                                       HasPhotos = ReaderHelpers.BoolTryParseDefault(s.Attribute("HasPhotos").Value, false),
                                       NeighborhoodId = ReaderHelpers.IntTryParseDefault(s.Attribute("NeighborhoodId").Value, 0),
                                       DatePosted = ReaderHelpers.DateTryParse(s.Attribute("DatePosted").Value),
                                       CreationDate = ReaderHelpers.DateTryParse(s.Attribute("CreationDate").Value),
                                       PrimaryPhoto = s.Attribute("PrimaryPhoto").Value,
                                       DateLastUpdated = ReaderHelpers.DateTryParse(s.Attribute("LastEditDate").Value), 
                                       Latitude= ReaderHelpers.DoubleTryParse  (
                                                (s.Attribute("Latitude") != null) ? s.Attribute("Latitude").Value : "0"),
                                       Longitude = ReaderHelpers.DoubleTryParse  (
                                                (s.Attribute("Longitude") != null) ? s.Attribute("Longitude").Value : "0")
                                   };

                    return listings.ToList<Listing>();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
                return null;
            }
        }
    }

    public static class ReaderHelpers
    {
        public static bool XAttributeBoolTryParse(XAttribute attr)
        {
            if (attr != null)
            {
                return ReaderHelpers.BoolTryParseDefault(attr.Value, false); 
            }
            return false;
        } 

        public static bool BoolTryParseDefault(string param, bool defaultvalue)
        {
            bool def = defaultvalue;
            bool.TryParse(param, out def);
            return def;
        }

        public static double DoubleTryParse(string param)
        {
            double ret; 
            Double.TryParse(param, out ret);
            return ret;
        }



        public static DateTime DateTryParse(string param)
        {
            DateTime ret;
            DateTime.TryParse(param, out ret);
            return ret;
        }

        public static int IntTryParseDefault(string param, int defaultvalue)
        {
            int i = defaultvalue;
            int.TryParse(param, out i);
            return i;
        }

        public static bool TryParseDefault(this bool it, string param, bool defaultvalue)
        {
            bool def = defaultvalue;

            bool.TryParse(param, out def);
            return def;
        }
    } 
}
